// config
package main

import (
	"encoding/json"
	"os"
)

type S3Config struct {
	AccessKey  string `json:"access_key"`
	SecretKey  string `json:"secret_key"`
	Bucket     string `json:"bucket"`
	Region     string `json:"region"`
	PrefixPath string `json:"prefix"`
}

type OSSConfig struct {
	AccessKey  string `json:"access_key"`
	SecretKey  string `json:"secret_key"`
	Bucket     string `json:"bucket"`
	EndPoint   string `json:"endpoint"`
	PrefixPath string `json:"prefix"`
}

type CloudFrontConfig struct {
	Enable bool   `json:"enable"`
	Host   string `json:"host"`
}

type HttpConfig struct {
	WebRoot string `json:"root"`
	Listen  string `json:"listen"`
}

type StorageConfig struct {
	S3  *S3Config  `json:"s3"`
	OSS *OSSConfig `json:"aliyun-oss"`
}

type PlistConfig struct {
	BasePath   string            `json:"base"`
	Template   string            `json:"tpl"`
	TempPath   string            `json:"tmp"`
	S3         *S3Config         `json:"s3"`
	CloudFront *CloudFrontConfig `json:"cloud-front"`
	Web        *HttpConfig       `json:"web"`
	Storage    *StorageConfig    `json:"storage"`
	WeChat     *WeChatConfig     `json:"wechat"`
	SendGrid   *SendGridConfig   `json:"sendgrid"`
	Auth       bool              `json:"auth"`
	sava_file  string
}

type SendGridConfig struct {
	FromName  string `json:"from_name"`
	FromEmail string `json:"from_email"`
	ApiKey    string `json:"api_key"`
}

func NewConfig(filename string) (err error, c *PlistConfig) {
	c = &PlistConfig{}
	c.sava_file = filename
	err = c.load(filename)
	return
}

func (c *PlistConfig) load(filename string) error {
	file, err := os.Open(filename)
	if err != nil {
		log.Error(err)
		return err
	}
	defer file.Close()
	decoder := json.NewDecoder(file)
	err = decoder.Decode(c)
	if err != nil {
		log.Error(err)
	}
	return err
}

func (c *PlistConfig) Save() error {
	file, err := os.Create(c.sava_file)
	if err != nil {
		log.Error(err)
		return err
	}
	defer file.Close()
	data, err := json.MarshalIndent(c, "", "    ")
	if err != nil {
		log.Error(err)
		return err
	}
	_, err = file.Write(data)
	if err != nil {
		log.Error(err)
	}
	return err
}

func (this *PlistConfig) Clone() *PlistConfig {
	
	return &PlistConfig{
		BasePath:   this.BasePath,
		Template:   this.Template,
		TempPath:   this.TempPath,
		S3:         this.S3,
		Storage:	this.Storage,
		CloudFront: this.CloudFront,
		sava_file:  this.sava_file,
	}
}
